package org.dylan.web.util;

import javax.servlet.http.HttpServletRequest;

/**
 * 浏览器工具类
 * 
 * @author dylan
 * 
 */
public class BrowserUtils {
	/**
	 * 通过获取头部的"USER-AGENT"来判断是否是IE浏览器
	 * 
	 * @param request
	 * @return
	 */
	public static boolean isIE(HttpServletRequest request) {
		return request.getHeader("USER-AGENT").indexOf("MSIE") > 0 ? true
				: false;
	}

	/**
	 * 获取IE版本
	 * 
	 * @param request
	 * @return
	 */
	public static Double getIEversion(HttpServletRequest request) {
		Double version = 0.0;
		String userAgent = request.getHeader("USER-AGENT");
		if (checkBrowserType(userAgent, "MSIE 10.0")) {
			version = 10.0;
		} else if (checkBrowserType(userAgent, "MSIE 9.0")) {
			version = 9.0;
		} else if (checkBrowserType(userAgent, "MSIE 8.0")) {
			version = 8.0;
		} else if (checkBrowserType(userAgent, "MSIE 7.0")) {
			version = 7.0;
		} else if (checkBrowserType(userAgent, "MSIE 6.0")) {
			version = 6.0;
		}
		return version;
	}

	/**
	 * 获取浏览器类型
	 * 
	 * @param request
	 * @return
	 */
	public static BrowserType getBrowserType(HttpServletRequest request) {
		BrowserType browserType = BrowserType.Other;
		String userAgent = request.getHeader("USER-AGENT");
		if (checkBrowserType(userAgent, "msie 10.0")) {
			browserType = BrowserType.IE10;
		} else if (checkBrowserType(userAgent, "MSIE 9.0")) {
			browserType = BrowserType.IE9;
		} else if (checkBrowserType(userAgent, "MSIE 8.0")) {
			browserType = BrowserType.IE8;
		} else if (checkBrowserType(userAgent, "MSIE 7.0")) {
			browserType = BrowserType.IE7;
		} else if (checkBrowserType(userAgent, "MSIE 6.0")) {
			browserType = BrowserType.IE6;
		} else if (checkBrowserType(userAgent, "Firefox")) {
			browserType = BrowserType.Firefox;
		} else if (checkBrowserType(userAgent, "Chrome")) {
			browserType = BrowserType.Chrome;
		} else if (checkBrowserType(userAgent, "Opera")) {
			browserType = BrowserType.Opera;
		} else if (checkBrowserType(userAgent, "Safari")) {
			browserType = BrowserType.Safari;
		} else if (checkBrowserType(userAgent, "Camino")) {
			browserType = BrowserType.Camino;
		}
		return browserType;
	}

	/**
	 * 通过头部的"USER-AGENT"信息检查浏览器类型是否是需要的浏览器类型
	 * 
	 * @param userAgent
	 * @param brosertype
	 *            期待的浏览器类型
	 * @return
	 */
	private static boolean checkBrowserType(String userAgent, String brosertype) {
		return userAgent.indexOf(brosertype) > 0 ? true : false;
	}
}
